#region File Description
//-----------------------------------------------------------------------------
// GameplayScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Xml.Linq;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion

namespace HOPE
{
    /// <summary>
    /// This screen implements the actual game logic. It is just a
    /// placeholder to get the idea across: you'll probably want to
    /// put some more interesting gameplay in here!
    /// </summary>
    class GameplayScreen : GameScreen
    {
        #region Fields

        ContentManager content;
        SpriteFont font16px;
        SpriteFont font36px;
        Texture2D testpage;
        Texture2D activepanel;
        Texture2D passivepanel;
        Texture2D statusbar;
        Texture2D davinaaktif;
        Texture2D latifupasif;
        Texture2D adrianapasif;
        Texture2D zakhaevpasif;
        Texture2D controlstick;
        Texture2D controlstickBoundary;
        //Texture2D jumpbutton;
        //Texture2D actionbutton;

        Vector2 controlstickpos = new Vector2(55, 369);
        Vector2 controlstickBoundarypos = new Vector2(34, 347);
        //Vector2 jumpbuttonpos = new Vector2(664, 346);
        //Vector2 actionbuttonpos = new Vector2(0, 0);
        Vector2 playerPosition = new Vector2(100, 100);
        Vector2 enemyPosition = new Vector2(100, 100);
        Vector2 testpagepos = new Vector2(0, 0);
        Vector2 activepanelpos = new Vector2(0, 0);
        Vector2 passivepanelpos = new Vector2(100, 0);
        Vector2 statusbarpos = new Vector2(131, 0);
        Vector2 davinaaktifpos = new Vector2(0, 0);
        Vector2 davinapasifpos = new Vector2(0, 0);
        Vector2 latifuaktifpos = new Vector2(0, 0);
        Vector2 latifupasifpos = new Vector2(200, 0);
        Vector2 zakhaevaktifpos = new Vector2(0, 0);
        Vector2 zakhaevpasifpos = new Vector2(120, 0);
        Vector2 adrianaaktifpos = new Vector2(0, 0);
        Vector2 adrianapasifpos = new Vector2(267, 0);

        //bool isActionButtonClicked;
        //bool isJumpButtonClicked;



        Random random = new Random();

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);


            EnabledGestures = GestureType.Tap;

        }


        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");


            LoadAssets();


            

            // A real game would probably have more content than this sample, so
            // it would take longer to load. We simulate that by delaying for a
            // while, giving you a chance to admire the beautiful loading screen.
            Thread.Sleep(1000);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();

            base.LoadContent();
        }


        /// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }

        public void LoadAssets()
        {
            // Loads the animation dictionary from an xml file
            //animations = new Dictionary<string, Animation>();
            //LoadAnimationFromXML();

            // Loads all textures that are required
            LoadTextures();

            // Create all game components
            CreateGameComponents();
        }

        #region private argument(load animation)
        //private void LoadAnimationFromXML()
        //{
        //    XDocument doc = XDocument.Load
        //        ("Content/Textures/AnimationDefinitions.xml");
        //    XName = XName.Get("Definition");
        //    var definitions = doc.Document.Descendants(name);

            //loop all definitons in the XML
        //    foreach (var animationDefinition in definitions)
        //    {
        //        // Get the name of the animation
        //        string animationAlias = animationDefinition.Attribute("Alias").Value;
        //        Texture2D texture =
        //            ScreenManager.Game.Content.Load<Texture2D>
        //            (animationDefinition.Attribute("SheetName").Value);

        //        // Get the frame size (width & height)
        //        Point frameSize = new Point();
        //        frameSize.X = int.Parse(
        //            animationDefinition.Attribute("FrameWidth").Value);
        //        frameSize.Y = int.Parse(
        //            animationDefinition.Attribute("FrameHeight").Value);

        //        // Get the frames sheet dimensions
        //        Point sheetSize = new Point();
        //        sheetSize.X = int.Parse(
        //            animationDefinition.Attribute("SheetColumns").Value);
        //        sheetSize.Y = int.Parse(
        //            animationDefinition.Attribute("SheetRows").Value);



        //        Animation animation = new Animation(texture, frameSize, sheetSize);

        //        // Checks for sub-animation definition
        //        if (animationDefinition.Element("SubDefinition") != null)
        //        {
        //            int startFrame = int.Parse(
        //                animationDefinition.Element("SubDefinition")
        //                .Attribute("StartFrame").Value);

        //            int endFrame = int.Parse
        //                (animationDefinition.Element("SubDefinition")
        //                .Attribute("EndFrame").Value);

        //            animation.SetSubAnimation(startFrame, endFrame);
        //        }

        //        if (animationDefinition.Attribute("Speed") != null)
        //        {
        //            animation.SetFrameInterval(
        //                TimeSpan.FromMilliseconds(
        //                double.Parse(animationDefinition.Attribute("Speed").Value)));
        //        }

        //        // If the definition has an offset defined - it should be  
        //        // rendered relative to some element/animation
        //        if (null != animationDefinition.Attribute("OffsetX") &&
        //            null != animationDefinition.Attribute("OffsetY"))
        //        {
        //            animation.Offset = new Vector2(int.Parse
        //                (animationDefinition.Attribute("OffsetX").Value),
        //                int.Parse(animationDefinition.Attribute("OffsetY").Value));
        //        }

        //        animations.Add(animationAlias, animation);
        //    }
        //}

        #endregion

        #region private argument(load textures)
        private void LoadTextures()
        {
            //load font
            font16px = content.Load<SpriteFont>("Textures/Interface/Fonts/GameScreenFont16px");
            font36px = content.Load<SpriteFont>("Textures/Interface/Fonts/GameScreenFont36px");

            //load background
            testpage = content.Load<Texture2D>("Textures/SplashScreen/splashscreen");

            //load inteface
            activepanel = content.Load<Texture2D>("Textures/Interface/StatusBar/Panel/activepanel");
            passivepanel = content.Load<Texture2D>("Textures/Interface/StatusBar/Panel/passivepanel");
            statusbar = content.Load<Texture2D>("Textures/Interface/StatusBar/Panel/statusbar");
            //char interface
            davinaaktif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Active/davinaaktif");
            //davinapasif = content.Load<Texture2D>("");
            //latifuaktif = content.Load<Texture2D>("");
            latifupasif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Passive/latifupasif");
            //zakhaevaktif = content.Load<Texture2D>("");
            zakhaevpasif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Passive/zakhaevpasif");
            //adrianaaktif = content.Load<Texture2D>("");
            adrianapasif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Passive/adrianapasif");

            //load control
            controlstick = content.Load<Texture2D>("Textures/GamePlay/Control/controlstick");
            controlstickBoundary = content.Load<Texture2D>("Textures/Gameplay/Control/controlstickBoundary");
            //jumpbuttonpos = content.Load<Textures2D>("Textures/Gameplay/Control/jumpbutton");
            //actionbuttonpos = content.Load<Textures2D>("Textures/Gameplay/Control/actionbutton");
        }
#endregion

        #region private argument(create game components)
        private void CreateGameComponents()
        {

        }
        #endregion

        #endregion

        #region Update and Draw


        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you tab away to a different application.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            if (IsActive)
            {
                // Apply some random jitter to make the enemy move around.
                const float randomization = 10;

                enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization;
                enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization;

                // Apply a stabilizing force to stop the enemy moving off the screen.
                //Vector2 targetPosition = new Vector2(
                //    ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2, 
                //    200);

                //enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f);

                // TODO: this game isn't very fun! You could probably improve
                // it by inserting something more interesting in this space :-)
            }
        }


        /// <summary>
        /// Lets the game respond to player input. Unlike the Update method,
        /// this will only be called when the gameplay screen is active.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            if (input == null)
                throw new ArgumentNullException("input");

            // Look up inputs for the active player profile.
            int playerIndex = (int)ControllingPlayer.Value;

            KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
            GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

            // if the user pressed the back button, we return to the main menu
            PlayerIndex player;
            if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player))
            {
                LoadingScreen.Load(ScreenManager, false, ControllingPlayer, new BackgroundScreen(), new MainMenuScreen());
            }
            else
            {
                // Otherwise move the player position.
                Vector2 movement = Vector2.Zero;

                if (keyboardState.IsKeyDown(Keys.Left))
                    movement.X--;

                if (keyboardState.IsKeyDown(Keys.Right))
                    movement.X++;

                if (keyboardState.IsKeyDown(Keys.Up))
                    movement.Y--;

                if (keyboardState.IsKeyDown(Keys.Down))
                    movement.Y++;

                Vector2 thumbstick = gamePadState.ThumbSticks.Left;

                movement.X += thumbstick.X;
                movement.Y -= thumbstick.Y;

                if (movement.Length() > 1)
                    movement.Normalize();

                playerPosition += movement * 2;
            }
        }


        /// <summary>
        /// Draws the gameplay screen.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // This game has a blue background. Why? Because!
            ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                               Color.CornflowerBlue, 0, 0);

            // Our player and enemy are both actually just text strings.
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

            //spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green);

            //spriteBatch.DrawString(gameFont, "Insert Gameplay Here",
            //                       enemyPosition, Color.DarkRed);
            //Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth);
            spriteBatch.Draw(testpage, testpagepos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1);
            spriteBatch.Draw(statusbar, statusbarpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.99f);
            spriteBatch.Draw(activepanel, activepanelpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.98f);
            spriteBatch.Draw(passivepanel, passivepanelpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.97f);
            spriteBatch.Draw(controlstick, controlstickpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.1f);
            spriteBatch.Draw(controlstickBoundary, controlstickBoundarypos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.11f);
            spriteBatch.Draw(davinaaktif, davinaaktifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.8f, 0.8f), SpriteEffects.None, 0.96f);
            spriteBatch.Draw(latifupasif, latifupasifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.8f, 0.8f), SpriteEffects.None, 0.95f);
            spriteBatch.Draw(zakhaevpasif, zakhaevpasifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.6f, 0.6f), SpriteEffects.None, 0.94f);
            spriteBatch.Draw(adrianapasif, adrianapasifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.6f, 0.6f), SpriteEffects.None, 0.94f);


            spriteBatch.End();

            // If the game is transitioning on or off, fade it out to black.
            if (TransitionPosition > 0)
                ScreenManager.FadeBackBufferToBlack(1f - TransitionAlpha);
        }


        #endregion
    }
}
